import { AUTH_KEY } from './../decorator/roles.decorator';
import { ExecutionContext, Injectable, UnauthorizedException } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { AuthGuard } from "@nestjs/passport";
import { Observable } from "rxjs";

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {

    // 是否跳过token认证的
    private skipFlag: boolean;
    constructor(private readonly reflector: Reflector) {
        super();
    }

    canActivate(
        context: ExecutionContext,
    ): boolean | Promise<boolean> | Observable<boolean> {
        /**
         *  获取控制器的原数据来判断是否对token 认证放行处理
         */
        const list = this.reflector.getAll<boolean[]>(AUTH_KEY, [context.getHandler(), context.getClass()]);
        this.skipFlag = list.some(item => item === true);
        return super.canActivate(context);
    }

    // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
    handleRequest(err:any, user:any, info):any {
        if (this.skipFlag) return true;
        // 可以抛出一个基于info或者err参数的异常
        if (err || !user) {
            throw err || new UnauthorizedException();
        }
        return user;
    }
}   